package com.onlineshop.controller;

import com.onlineshop.dao.ProductDao;
import com.onlineshop.entity.Product;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@WebServlet("/user_home")
public class UserHomeServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();

    // 预定义分类列表
    private static final List<String> CATEGORIES = Arrays.asList(
            "饮品类", "食品类", "零食类", "生活用品类", "药品类", "水果类", "肉类", "蔬菜类"
    );

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取所有商品
        List<Product> allProducts = productDao.getAllProducts();

        // 获取搜索关键词
        String searchKeyword = request.getParameter("search");

        // 获取选中的分类（如果有）
        String selectedCategory = request.getParameter("category");

        // 过滤商品
        List<Product> filteredProducts = filterProducts(allProducts, selectedCategory);

        // 按关键词搜索
        if (searchKeyword != null && !searchKeyword.isEmpty()) {
            final String keyword = searchKeyword.toLowerCase();
            filteredProducts = filteredProducts.stream()
                    .filter(p -> matchesSearch(p, keyword))
                    .collect(Collectors.toList());
        }

        // 按分类筛选
        filteredProducts = filterProducts(filteredProducts, selectedCategory);

        // 提取所有分类（从商品描述中）
        Set<String> allCategories = extractCategories(allProducts);

        // 设置请求属性
        request.setAttribute("products", filteredProducts);
        request.setAttribute("categories", allCategories);
        request.setAttribute("selectedCategory", selectedCategory);
        request.setAttribute("searchKeyword", searchKeyword);

        request.getRequestDispatcher("/user_home.jsp").forward(request, response);
    }

    // 检查商品是否匹配搜索关键词
    private boolean matchesSearch(Product product, String keyword) {
        // 检查商品名称
        if (product.getName() != null && product.getName().toLowerCase().contains(keyword)) {
            return true;
        }

        // 检查商品描述
        if (product.getDescription() != null && product.getDescription().toLowerCase().contains(keyword)) {
            return true;
        }

        // 检查分类标签
        if (product.getDescription() != null) {
            String description = product.getDescription().toLowerCase();
            for (String cat : CATEGORIES) {
                if (description.contains("[" + cat.toLowerCase() + "]") &&
                        cat.toLowerCase().contains(keyword)) {
                    return true;
                }
            }
        }

        return false;
    }

    // 过滤商品
    private List<Product> filterProducts(List<Product> products, String category) {
        if (category == null || category.isEmpty() || "全部商品".equals(category)) {
            return products;
        }

        return products.stream()
                .filter(p -> p.getDescription() != null && p.getDescription().contains(category))
                .collect(Collectors.toList());
    }

    // 从商品描述中提取分类
    private Set<String> extractCategories(List<Product> products) {
        Set<String> categories = new HashSet<>(CATEGORIES);
        categories.add("全部商品"); // 添加"全部商品"选项

        // 从商品描述中提取额外的分类
        products.forEach(p -> {
            if (p.getDescription() != null) {
                for (String cat : CATEGORIES) {
                    if (p.getDescription().contains(cat)) {
                        categories.add(cat);
                    }
                }
            }
        });

        return categories;
    }
}